<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="450px" :title="`${drawerProps.title}用户`">
    <el-form
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="头像" prop="userPicId">
        <UploadImg v-model:image-id="drawerProps.row.userPicId" :drag="false" border-radius="50%">
          <template #empty>
            <el-icon><Avatar /></el-icon>
            <span>请上传头像</span>
          </template>
        </UploadImg>
      </el-form-item>
      <el-form-item label="姓名" prop="userName">
        <el-input v-model="drawerProps.row!.userName" clearable></el-input>
      </el-form-item>
      <el-form-item label="登录名称" prop="loginName">
        <el-input v-model="drawerProps.row!.loginName" clearable></el-input>
      </el-form-item>
      <el-form-item v-if="drawerProps.title.indexOf('新增') != -1" label="密码" prop="password">
        <el-input
          type="password"
          placeholder="密码需包含数字、大小写字母、特殊字符，长度大于8位"
          v-model="drawerProps.row!.password"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <common-select
          data-key="SEX"
          placeholder="请选择性别"
          :request-api="() => apiService.findClassify('SEX')"
          v-model="drawerProps.row!.sex"
        ></common-select>
      </el-form-item>
      <el-form-item label="工号" prop="workNo">
        <el-input v-model="drawerProps.row!.workNo" clearable></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="drawerProps.row!.email" clearable></el-input>
      </el-form-item>
      <el-form-item label="岗位" prop="post">
        <common-select
          data-key="user_post"
          placeholder="请选择岗位"
          :request-api="() => apiService.findClassify('user_post')"
          v-model="drawerProps.row!.post"
        ></common-select>
      </el-form-item>
      <el-form-item label="所属组织" prop="orgId">
        <cascader-select
          data-key="orgs"
          :request-api="() => apiService.findTree('orgs', {}, { sort: { sort: 1 }, fields: ['_id', 'name', 'pid'] })"
          :config="{ label: 'name', value: '_id', checkStrictly: true }"
          v-model:item-value="drawerProps.row!.orgId"
        ></cascader-select>
      </el-form-item>
      <el-form-item label="排序" prop="value">
        <el-input v-model="drawerProps.row!.sort" clearable></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <common-select
          data-key="DATA_STATE"
          placeholder="请选择状态"
          :request-api="() => apiService.findClassify('DATA_STATE')"
          v-model="drawerProps.row!.state"
        ></common-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="UserDrawer">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { Users } from "@/api/types/base";
import apiService from "@/api/services/apiService";
import commonSelect from "@/components/SelectFilter/common-select.vue";
import { encrypt, decrypt } from "@/api/services/encrypt";
import UploadImg from "@/components/Upload/Img.vue";
import cascaderSelect from "@/components/SelectFilter/cascader-select.vue";
import { isPasswordStrong } from "@/utils";

const rules = reactive({
  userName: [{ required: true, message: "请输入用户名称" }],
  loginName: [{ required: true, message: "请输入登录名称" }],
  password: [{ required: true, message: "请输入密码" }]
});

interface DrawerProps {
  title: string;
  tbName: string;
  isView: boolean;
  row: Partial<Users>;
  api?: (tabName: string, params: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  tbName: "",
  row: {}
});

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  if (drawerProps.value.title.indexOf("编辑") != -1) {
    if (drawerProps.value.row.password) {
      drawerProps.value.row.password = decrypt(drawerProps.value.row.password, drawerProps.value.row.loginName);
    }
  }
  drawerVisible.value = true;
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      if (isPasswordStrong(drawerProps.value.row.password)) {
        // 密码进行MD5加密
        drawerProps.value.row.password = encrypt(drawerProps.value.row.password!, drawerProps.value.row.loginName);
        await drawerProps.value.api!(drawerProps.value.tbName, drawerProps.value.row);
        ElMessage.success({ message: `${drawerProps.value.title}成功！` });
        drawerProps.value.getTableList!();
        drawerVisible.value = false;
      } else {
        ElMessage.warning({ message: "密码强度不够！" });
      }
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  acceptParams
});
</script>
@/api/types
